<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Logistics;
use App\Http\Requests\LogisticsRequest;
use Storage;
use Excel;

class LogisticsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('admin.logistics.index');
    }

    public function data(Request $request)
    {
        $model = Logistics::query();
        if($request->get('order_num')){
            $model = $model->where('order_num',$request->get('order_num'));
        }
        if($request->get('accept_phone')){
            $model = $model->where('accept_phone',$request->get('accept_phone'));
        }
        $res = $model->orderBy('sent_at','desc')->paginate($request->get('limit',30))->toArray();
        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res['total'],
            'data'  => $res['data']
        ];
        return response()->json($data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.logistics.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(LogisticsRequest $request)
    {
        if(Logistics::create($request->all())){
            return redirect()->to(route('admin.logistics'))->with(['status'=>'添加成功']);
        }
        return back()->with(['status'=>'添加失败']);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $logistics = Logistics::findOrFail($id);
        return view('admin.logistics.edit',compact('logistics'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(LogisticsRequest $request, $id)
    {
        $logistics = Logistics::findOrFail($id);
        if($logistics->update($request->all())){
            return redirect()->to(route('admin.logistics'))->with(['status'=>'更新成功']);
        }
        return back()->with(['status'=>'更新失败']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $ids = $request->get('ids',[]);
        if (empty($ids)){
              return response()->json(['code'=>1,'msg'=>'请选择删除项']);
        }

        if (Logistics::destroy($ids)){
            return response()->json(['code'=>0,'msg'=>'已删除']);
        }
        return response()->json(['code'=>1,'msg'=>'删除失败']);
    }

    public function import(Request $request)
    {
        set_time_limit(0);
        $file = $request->file('file');
        if ($file->isValid()){
            //上传文件
            $ext = $file->getClientOriginalExtension();
            if (strtolower($ext)!='xlsx'){
                return response()->json(['code'=>1,'msg'=>'请上传xlsx格式的文件']);
            }
            $fileName = uniqid().time().'.xlsx';
            $uploadBool = Storage::disk('local')->put($fileName, file_get_contents($file->getRealPath()));
            if (!$uploadBool){
                return ['code'=>1,'msg'=>'文件上传失败'];
            }
            $filePath = storage_path().'/app/'.$fileName;
            //导入数据
            try {
                Excel::load($filePath, function ($reader) {
                    $reader->ignoreEmpty();
                    foreach ($reader->all() as $value){
                        $data = array_combine([
                            'sent_at',
                            'company_name',
                            'order_num',
                            'goods_type',
                            'accept_name',
                            'accept_phone'
                        ],$value->toArray());
                        Logistics::create($data);
                    }
                });
                return ['code'=>0,'msg'=>'导入完成'];
            } catch (\Exception $e) {
                return ['code'=>1,'msg'=>$e->getMessage()];
            }
        }else{
            return ['code'=>1,'msg'=>$file->getErrorMessage()];
        }

    }

   public function truncate()
    {
        Logistics::truncate();
        return response()->json(['code'=>0,'msg'=>'清空完成']);
    }

}
